// Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC.  All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

#include "protos_generator/output.h"

#include <string>

#include "absl/strings/str_replace.h"

namespace protos_generator {
namespace {

namespace protobuf = ::google::protobuf;

}  // namespace

std::string StripExtension(absl::string_view fname) {
  size_t lastdot = fname.find_last_of('.');
  if (lastdot == std::string::npos) {
    return std::string(fname);
  }
  return std::string(fname.substr(0, lastdot));
}

std::string ToCIdent(absl::string_view str) {
  return absl::StrReplaceAll(str, {{".", "_"}, {"/", "_"}, {"-", "_"}});
}

std::string ToPreproc(absl::string_view str) {
  return absl::AsciiStrToUpper(ToCIdent(str));
}

void EmitFileWarning(const protobuf::FileDescriptor* file, Output& output) {
  output(
      R"cc(
        /* This file was generated by protos_generator (the upb C++ compiler) "
        from the input
         * file:
         *
         *     $0
         *
         * Do not edit -- your changes will be discarded when the file is
         * regenerated. */
      )cc",
      file->name());
  output("\n");
}

std::string MessageName(const protobuf::Descriptor* descriptor) {
  return ToCIdent(descriptor->full_name());
}

std::string FileLayoutName(const google::protobuf::FileDescriptor* file) {
  return ToCIdent(file->name()) + "_upb_file_layout";
}

std::string CHeaderFilename(const google::protobuf::FileDescriptor* file) {
  return StripExtension(file->name()) + ".upb.h";
}

std::string CSourceFilename(const google::protobuf::FileDescriptor* file) {
  return StripExtension(file->name()) + ".upb.c";
}

}  // namespace protos_generator
